package cn.slb.im.user.controller;

import cn.slb.im.common.utils.PageUtils;
import cn.slb.im.common.utils.R;
import cn.slb.im.user.entity.DeptEntity;
import cn.slb.im.user.service.DeptService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;


/**
 * 部门表
 *
 * @author nick
 * @email ld@qq.com
 * @date 2021-12-03 00:01:54
 */
@RestController
@RequestMapping("user/dept")
public class DeptController {
    @Autowired
    private DeptService deptService;


    /**
     * 查出所有部门，包括所有子部门，封装成树型结构组装起来
     *
     * @param params
     * @return
     */
    @RequestMapping("/list/tree")
    //@RequiresPermissions("user:dept:list")
    public R listTree(@RequestParam Map<String, Object> params) {
        List<DeptEntity> deptTreeList = deptService.listTree(params);
        return R.ok().put("data", deptTreeList);
    }

    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("user:dept:list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = deptService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("user:dept:info")
    public R info(@PathVariable("id") Long id) {
        DeptEntity dept = deptService.getOne(new LambdaQueryWrapper<DeptEntity>().eq(DeptEntity::getId, id)
                .eq(DeptEntity::getIsDelete, 0));
        return R.ok().put("dept", dept);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    //@RequiresPermissions("user:dept:save")
    public R save(@RequestBody DeptEntity dept) {
        deptService.save(dept);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("user:dept:update")
    public R update(@RequestBody DeptEntity dept) {
        deptService.updateById(dept);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("user:dept:delete")
    public R delete(@RequestBody Long[] ids) {
        List<DeptEntity> list = deptService.list(new LambdaQueryWrapper<DeptEntity>()
                .in(DeptEntity::getParentId, ids).eq(DeptEntity::getIsDelete, 0));
        if (!CollectionUtils.isEmpty(list)) {
            return R.error("不能直接删除该部门，请先删除其子部门");
        }
        deptService.deleteByIds(ids);
        return R.ok();
    }

}
